package com.example.java_chatroom1.controller;

import com.example.java_chatroom1.model.Result;
import com.example.java_chatroom1.model.User;
import com.example.java_chatroom1.server.FriendService;
import com.example.java_chatroom1.server.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/friend")
public class FriendController {
    @Autowired
    private FriendService friendService;

    @Autowired
    private MessageService messageService;

    @RequestMapping("/getFriendList")
    public Result<List<User>> getFriendByUserId(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        List<User> ret = friendService.getFriendByUserId(userId);
        return Result.success(ret);
    }

    @RequestMapping("/isSessionExist")
    public Result<Integer> isSessionExist(HttpServletRequest request,Integer friendId) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        List<Integer> sessionIds = messageService.getSessionIdByUserId(userId);
        for (Integer n : sessionIds) {
            int id = messageService.getUserIdBySessionId(n,userId);
            if (id == friendId) return Result.success(n);
        }
        return Result.success(-1);
    }
}
